package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


// 收货地址
@Service
@Transactional
public class AddressServiceImpl implements AddressService {
    //注入
    @Autowired
    private AddressMapper addressMapper;
   //地址列表
    @Override
    public List<Address> findList() {
    //构建条件
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId, UserHolder.get().getId()); //用户id
        //查询并返回
        return addressMapper.selectList(qw);
    }

    //地址新增
    @Override
    public void save(Address address) {
        //补全信息
        address.setUserId(UserHolder.get().getId());
        //用户id
        address.setIsDefault(0); //非默认地址
       //新增地址
        addressMapper.insert(address);

    }
    //设为默认地址
    @Override
    public void setDefault(Long id) {
        //1.把当前用户下所有的收获地址设置为非默认
        //1-1设置修改内容
        Address address1 = new Address();
        address1.setIsDefault(0); //设置地址为非默认
        //1-2设置用户id为条件
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getUserId,UserHolder.get().getId());
        //1-3更新
        addressMapper.update(address1,qw);
        //2.将当前收货地址设置为默认
        Address address2 = new Address();
        address2.setId(id);//收货地址id
        address2.setIsDefault(1);//设为默认地址
        addressMapper.updateById(address2);

    }

    //去结算,查询默认地址
    @Override
    public Address findDefault() {
        //构建条件
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getIsDefault , 1); //默认值为1
        qw.eq(Address::getUserId,UserHolder.get().getId()); //用户id
        //调用mapper查询并返回
        return addressMapper.selectOne(qw);
    }

    //回显地址
    @Override
    public Address findById(Long id) {
        //1.先查地址
        Address address = addressMapper.selectById(id);
        /*//2.根据用户id查询地址
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        qw.eq(Address::getId,id);*/
        /*//调用mapper
         address = addressMapper.selectOne(qw);*/
        //返回地址
        return address;
    }

    //修改地址
    @Override
    public void updateById(Address address) {
       //1.修改地址的基本信息
       addressMapper.updateById(address);
       //根据地址id修改原来地址
        LambdaQueryWrapper<Address> qw = new LambdaQueryWrapper<>();
        //删除原来地址
        addressMapper.delete(qw);
        //3.新增地址
        addressMapper.insert(address);


    }

    //删除地址
    @Override
    public void deleteById(Long ids) {
        //删除地址
      addressMapper.deleteById(ids);

    }
}
